<template>
  <Table ref="tableRef" :columns="columns" :data="loadData" :alert="false" bordered>
    <template #operator>
      <div class="table-search">
        <div>
          <span class="table-search-box">
            <a-input
              v-model:value="searchValue"
              placeholder="请输入空间名称，访问级别搜索"
              style="width: 300px"
              allowClear
            >
              <template #prefix>
                <SvgIcon class="iconDef" :name="'search'" :color="'#d9d9d9'" width="16" height="16" />
              </template>
            </a-input>
          </span>
        </div>
        <div class="table-search-btn">
          <a-button class="actionBtn" type="primary" ghost @click="tableRef.refresh(true)">
            <SvgIcon class="iconDef" :name="'search'" :color="'#2590FF'" width="16" height="16" />
            查询
          </a-button>

          <a-button class="actionBtn" type="primary" ghost @click="refreshTable">
            <SvgIcon class="iconDef" :name="'refresh'" :color="'#2590FF'" width="16" height="16" />
            重置
          </a-button>
        </div>
      </div>
      <div style="margin-top: 16px">
        <a-button type="primary" @click="addNamespace">
          <PlusOutlined />
          新增命名空间
        </a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
      <template v-if="column.dataIndex === 'accessLevel'">{{
        AccessLevelNames[record.accessLevel as keyof typeof AccessLevelNames]
      }}</template>
      <template v-if="column.dataIndex === 'encryptStrategy'"
        >{{ record.encryptStrategy == EncryptStrategyValues.Manual ? EncryptStrategyNames.Manual : '' }}
      </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation">
          <a @click="handelDetail(record)">详情</a>
          <a
            @click="handelEdit(record)"
            v-auth="{
              objectId: artifactObj.uuid,
              objectType: ResourceType.repository,
              role: ArtifactRole.manager,
            }"
            >编辑</a
          >
          <a
            @click="handelDelete(record)"
            v-auth="{
              objectId: artifactObj.uuid,
              objectType: ResourceType.repository,
              role: ArtifactRole.manager,
            }"
            >删除</a
          >
        </div>
      </template>
    </template>
  </Table>

  <BasicModal
    ref="showActionModal"
    :title="`${ModalName[showType]}-命名空间`"
    width="600px"
    :confirmLoading="editNameSpaceLoading"
    @emit-callback-fn="modalCallbackFn"
  >
    <template #content><SchemaForm ref="formRef" /></template>
  </BasicModal>
</template>

<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue';
import {
  queryArtifactRespositoryNamespaceListFun,
  putArtifactRespositoryNamespaceList,
  deleteArtifactRespositoryNamespaceListFun,
  addArtifactRespositoryNamespaceListFun,
} from '@/api/artifactRepository';
import { Modal, message } from 'ant-design-vue';
import { ModalName, ModalType } from '@/enums/commonEnum';
import { createVNode } from 'vue';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import { useArtifactRepositoryStore } from '@/store/modules/artifactRepository';
import { ResourceType } from '@/enums/pipelineEnum';
import { ArtifactRole } from '@/enums/artifactRepositoryEnum';
const artifactRepositoryStore = useArtifactRepositoryStore();
const { artifactObj } = artifactRepositoryStore;

const columns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 60 },
  { dataIndex: 'name', title: '空间名称', align: 'center', ellipsis: true },
  { dataIndex: 'accessLevel', title: '访问级别', align: 'center', ellipsis: true },
  { dataIndex: 'tag', title: '标签', align: 'center', ellipsis: true },
  // { dataIndex: 'encryptStrategy', title: '加密策略', align: 'center', ellipsis: true },
  { dataIndex: 'createTime', title: '创建时间', align: 'center', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];
enum EncryptStrategyNames {
  Manual = '手动',
}

enum EncryptStrategyValues {
  Manual = 1,
}

enum AccessLevelValues {
  PUBLIC = 'PUBLIC',
  PRIVATE = 'PRIVATE',
}

enum AccessLevelNames {
  PUBLIC = '公开',
  PRIVATE = '私有',
}

// const strategyOptions = [{ label: EncryptStrategyNames.Manual, value: EncryptStrategyValues.Manual }];
const accessLevelOptions = [
  { label: AccessLevelNames.PUBLIC, value: AccessLevelValues.PUBLIC },
  { label: AccessLevelNames.PRIVATE, value: AccessLevelValues.PRIVATE },
];

const [SchemaForm, formRef] = useForm({
  schemas: [
    {
      field: 'name',
      label: '空间名称',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
    {
      field: 'accessLevel',
      label: '访问级别',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      componentProps: {
        options: accessLevelOptions,
      },
      component: 'Select',
    },
    {
      field: 'tag',
      label: '标签',
      labelWidth: 90,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
    // {
    //   field: 'encryptStrategy',
    //   label: '加密策略',
    //   labelWidth: 90,
    //   colProps: {
    //     span: 24,
    //   },
    //   componentProps: {
    //     options: strategyOptions,
    //   },
    //   component: 'Select',
    // },
  ] as FormSchema[],
});

const showType = ref<ModalType>(ModalType.detail);
const showActionModal = ref<any>();
const tableRef = ref<any>('');
const searchValue = ref<string>('');
const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      condition: searchValue.value,
      artifactUuid: artifactObj.uuid,
    },
  };
  const data = await getList(parameObj);
  return data;
};

//获取表格数据
const getList = async (parameObj: any) => {
  return await queryArtifactRespositoryNamespaceListFun(parameObj).then((res) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records: res?.records || [],
    };
    return data;
  });
};
const editNameSpaceLoading = ref<boolean>(false);
const modalCallbackFn = async (obj: any) => {
  const data = await formRef.validate();
  editNameSpaceLoading.value = true;
  if (showType.value == ModalType.add) {
    await addArtifactRespositoryNamespaceListFun({
      artifactUuid: artifactObj.uuid,
      ...data,
    })
      .then(() => {
        message.success('新增成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
      })
      .finally(() => {
        editNameSpaceLoading.value = false;
      });
  }
  if (showType.value == ModalType.edit) {
    await putArtifactRespositoryNamespaceList({
      artifactUuid: artifactObj.uuid,
      uuid: obj.propsData.uuid,
      ...data,
    })
      .then(() => {
        message.success('编辑成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
      })
      .finally(() => {
        editNameSpaceLoading.value = false;
      });
  }
};

const refreshTable = () => {
  searchValue.value = '';
  tableRef.value.refresh(true);
};

const addNamespace = () => {
  showType.value = ModalType.add;
  showActionModal.value.showModal();
};

const handelDetail = (record: any) => {
  showType.value = ModalType.detail;
  showActionModal.value.showModal(record, '关闭');
  nextTick(() => {
    formRef.setSchemaFormProps({ disabled: true });
    formRef.setFieldsValue(record);
  });
};

const handelEdit = (record: any) => {
  showType.value = ModalType.edit;
  showActionModal.value.showModal(record);
  nextTick(() => {
    formRef.setFieldsValue(record);
  });
};

const handelDelete = async (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode('div', { style: 'color:black;' }, `确定要删除“命名空间：${record.name}”这一项数据吗？`),
    async onOk() {
      await deleteArtifactRespositoryNamespaceListFun(record.uuid).then(() => {
        message.success('删除成功');
        tableRef.value.refresh(true);
      });
    },
    onCancel() {},
  });
};
</script>

<style lang="less" scoped>
.table-search {
  border-bottom: 1px solid #e7eff8;
  padding-bottom: 16px;
}
</style>
